package service

import (
	"fmt"
	"go-admin-auth/app/dal"
	"go-admin-auth/app/lib/treetool"
	"go-admin-auth/app/models"
	"go-admin-auth/httpapi/dto"
	"go-admin-auth/httpapi/dtoex"
)

type organizationSrv struct{}

var (
	OrganizationSrv = &organizationSrv{}
)

func (srv *organizationSrv) Query(f *dto.OrganizationQueryForm) (*dtoex.OrganizationQueryResEx, error) {
	res, err := dal.OrganizationDAO.Query(f)
	if err != nil {
		return nil, err
	}
	return (*dtoex.OrganizationQueryRes)(res).Extend(), nil
}

func (srv *organizationSrv) Get(id int) (*models.TOrganization, error) {
	return dal.OrganizationDAO.Get(id)
}

func (srv *organizationSrv) GetMulti(idList []int) (map[int]models.TOrganization, error) {
	return dal.OrganizationDAO.GetMulti(idList)
}

func (srv *organizationSrv) GetSubList(parentPath string) ([]models.TOrganization, error) {
	form := new(dto.OrganizationQueryForm)
	form.Page = 1
	form.Psize = 10000
	form.ParentPath = parentPath
	res, err :=  dal.OrganizationDAO.Query(form)
	if err != nil {
		return nil, err
	}

	return res.List, nil
}

func (srv *organizationSrv) Insert(m *models.TOrganization) error {
	parent, _ := dal.OrganizationDAO.Get(m.ParentId)
	m.Path = fmt.Sprintf("%s%v/", parent.Path, parent.Id)
	m.Level = parent.Level + 1

	return dal.OrganizationDAO.Insert(m)
}

func (srv *organizationSrv) Update(m *models.TOrganization) error {
	return dal.OrganizationDAO.Update(m)
}

func (srv *organizationSrv) Delete(id int) error {
	return dal.OrganizationDAO.Delete(id)
}

func (srv *organizationSrv) RealDelete(id int) error {
	return dal.OrganizationDAO.RealDelete(id)
}

func (srv *organizationSrv) GetOrgSelectOptions(treeRootId int) ([]models.TOrganization, error) {
	form := new(dto.OrganizationQueryForm)
	list, err := dal.OrganizationDAO.GetList(form)
	if err != nil {
		return nil, err
	}

	for i, v := range list {
		list[i].Path = fmt.Sprintf("%s%v/", v.Path, v.Id)
	}

	tree := treetool.NewOrgTree(list, treeRootId)
	return tree.GetSelectOptions(), nil
}
